import { StoreOptions, MutationTree, ActionTree } from 'vuex'

export interface tabsViewState{
  tabList: Array<Tab>,
  activeKey: string,
  selectedKeys: string[],
  openKeys: string[],
}

export interface Tab{
  title: string,
  path: string,
  closable: boolean,
}

export default {
  namespaced: true,

  state: {
    tabList: [
      { title: '公告板', path: '/', closable: false },
    ],
    activeKey: '/',
    selectedKeys: ['/'],
    openKeys: [''],
  },

  mutations: {

    ADD_TAB(state, tab: Tab) {
      const hasTab = state.tabList.some(item => item.path === tab.path)

      if (!hasTab) {
        state.tabList.push(tab)
      }
    },

    REMOVE_TAB(state, path) {
      let activeKey = state.activeKey
      let lastIndex = 0

      state.tabList.forEach((pane, i) => {
        if (pane.path === path) {
          lastIndex = i - 1
        }
      })

      state.tabList = state.tabList.filter(item => item.path !== path)

      if (state.tabList.length && state.activeKey === path) {
        if (lastIndex >= 0) {
          activeKey = state.tabList[lastIndex].path
        } else {
          activeKey = state.tabList[0].path
        }
      }

      state.activeKey = activeKey
    },

    SET_SELECTED_KEYS(state, keys) {
      state.selectedKeys = keys
    },

    SET_ACTICVE_KEY(state, activeKey) {
      state.activeKey = activeKey
    },

    SET_OPEN_KEYS(state, openKeys) {
      state.openKeys = openKeys
    },

  } as MutationTree<tabsViewState>,

  actions: {
  } as ActionTree<tabsViewState, tabsViewState>,

} as StoreOptions<tabsViewState>
